package de.haw.HES.base;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;

public class PersistenceManager {

	private HibernateTemplate hibernateTemplate;
	private Session session;
	private SessionFactory sessionFactory;
	
	private static final String table= "Lieferung";

	public void setSessionFactory(SessionFactory sessionFactory) {
		
		this.sessionFactory = sessionFactory;
		this.hibernateTemplate = new HibernateTemplate(sessionFactory);
		this.session = sessionFactory.getCurrentSession();
		
	}
	
	private void createSession() {
		session = sessionFactory.getCurrentSession();
	}
	
	public void update(FachObjekt objekt) {
//		createSession();
		if(!session.isOpen()) {
			createSession();
		}
		session.beginTransaction();
		session.update(objekt);
		session.getTransaction().commit();
	}
	
	public void write(FachObjekt objekt) {
//		createSession();
		if(!session.isOpen()) {
			createSession();
		}
		session.beginTransaction();
		session.save(objekt);
		session.getTransaction().commit();
	}
	
	public void write(FachObjekt objekt,FachObjekt objekt2) {
//		createSession();
		session.beginTransaction();
		session.save(objekt);
		session.save(objekt2);
		session.getTransaction().commit();
	}
	
	@SuppressWarnings("unchecked")
	public <T extends FachObjekt> List<T> find(T type,String table) {
		return hibernateTemplate.find("from " + table);
	}
	
}
